package cn.zeronineten;

import java.util.Arrays;

/*
@李子宁
Happy,happy everyday!
冲鸭！
2020/9/17

*/
public class testSort {

    public static void main(String[] args) {
        int arr[] = {2,8,5,4,9,6,3,5,8,4,7,11};
        testSort sort = new testSort();
        sort.mergesort(arr,0,arr.length-1,new int[arr.length]);
        for (int i : arr) {
            System.out.println(i);
        }

    }

    //归并排序
    public void mergesort(int arr[],int left,int right,int[] tmp){
        if(left<right){
            int mid = (left+right)/2;
            mergesort(arr,left,mid,tmp);
            mergesort(arr,mid+1,right,tmp);

            merge(arr,left,mid,right,new int[arr.length]);
        }
    }
    public void merge(int arr[],int left,int mid,int right,int[] tmp){
        int i = left;
        int j = mid+1;
        int t = 0;
        while (i<=mid && j<=right){
            if (arr[i]<=arr[j]){
                tmp[t++] = arr[i++];

            }else{
                tmp[t++] = arr[j++];
            }
        }
        while (i<=mid){
            tmp[t++] = arr[i++];
        }
        while (j<=right){
            tmp[t++] = arr[j++];
        }

        t=0;
        int tmpLeft = left;
        while (tmpLeft < right){
            arr[tmpLeft++] = tmp[t++];
        }
    }

    //快排
    public void quickSort(int arr[],int left,int right){
        int l = left;
        int r = right;
        int pivot =arr[(left+right)/2];
        int tmp = 0;
        while (l<r){
            while (arr[l] < pivot){
               l++;
            }
            while (arr[r] > pivot){
                r--;
            }
            if (l>=r){
                break;
            }
            tmp  =arr[l];
            arr[l] = arr[r];
            arr[r] = tmp;

            if (arr[l]==pivot){
                r--;
            }
            if (arr[r] == pivot){
                l++;
            }
        }
            if (l==r){
                l+=1;
                r-=1;
            }
            if (left < r){
                quickSort(arr,left,r);
            }
            if (right > l){
                quickSort(arr,l,right);
            }

    }
}
